"use client";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { useSidebarStore } from "@/components/state/sidebar_state";
import { ComboboxDemo } from "@/components/custom/combobox";
import { useState } from "react";
import {
  FastResponse,
  PortProps,
  PortResponse,
} from "@/components/models/dataprops";
import { postData } from "@/components/utils/api";

const servers = [
  {
    label: "81服务器",
    value: "http://172.17.62.81/",
  },
  {
    label: "82服务器",
    value: "http://172.17.62.82/",
  },
];
function PortPage() {
  const updateSelected = useSidebarStore((state) => state.updateSelected);
  updateSelected("端口注册", "工具中心");

  // 声明几个变量
  const [server, setServer] = useState("");
  const [port, setPort] = useState<number>();
  const [maintainer, setMaintainer] = useState("");
  const [desc, setDesc] = useState("");

  const [msg, setMsg] = useState("");

  async function handleSubmit() {
    if (server === "") {
      setMsg("请选择服务器");
      return;
    }
    if (port === undefined) {
      setMsg("请输入端口");
      return;
    }
    if (maintainer === "") {
      setMsg("请输入维护人");
      return;
    }
    if (desc === "") {
      setMsg("请输入功能描述");
      return;
    }

    setMsg("");

    //开始访问服务器
    const payload: PortProps = {
      server: server,
      port: port.toString(),
      name: maintainer,
      des: desc,
    };
    try {
      const result = await postData<FastResponse<PortResponse>, PortProps>(
        "/port/register",
        payload
      );
      if (result.code === 200) {
        if (result.data.state === "success") {
          setMsg("端口注册成功");
        } else {
          setMsg("端口已被占用");
        }
      }
    } catch (error) {
      console.log("Error submitting data:", error);
      setMsg("请求失败，请稍后重试");
    }
  }

  return (
    <div className="grid grid-cols-[150px_auto] items-center text-sm">
      <div className="p-4 pl-2 text-end"> 服务器列表：</div>{" "}
      <ComboboxDemo items={servers} placehoder="服务器" onChange={setServer} />
      <div className="p-4 pl-2 text-end"> 端口：</div>{" "}
      <Input type="number" onChange={(e) => setPort(Number(e.target.value))} />
      <div className="p-4 pl-2 text-end"> 维护人：</div>{" "}
      <Input onChange={(e) => setMaintainer(e.target.value)} />
      <div className="p-4 pl-2 text-end"> 功能描述：</div>
      <Textarea
        placeholder="请输入功能描述"
        onChange={(e) => setDesc(e.target.value)}
      />
      <p></p>
      <div className="p-4 items-center">
        <button
          onClick={handleSubmit}
          className="p-2 w-full bg-emerald-700 rounded-md text-gray-100 font-semibold text-sm hover:bg-green-700 hover:text-gray-50"
        >
          注册端口
        </button>
      </div>
      <p></p>
      <p className="text-red-700 text-sm pl-6">{msg}</p>
    </div>
  );
}
export default PortPage;
